<template>
  <div class="form-container">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>活动管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/childActivity' }"
          >子活动列表</el-breadcrumb-item
        >
        <el-breadcrumb-item>添加子活动</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="form-content" style="background: #fff">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="设置子活动" name="1"></el-tab-pane>
        <el-tab-pane label="子活动配置" name="2"></el-tab-pane>
      </el-tabs>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="126px"
        v-if="activeName == '1'"
      >
        <el-form-item label="子活动名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入子活动名称"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="子活动编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入子活动编码"></el-input>
        </el-form-item> -->

        <el-form-item label="跳转页面地址" prop="pagepath">
          <el-input
            v-model="form.pagepath"
            placeholder="请输入跳转页面地址"
          ></el-input>
        </el-form-item>

        <el-form-item label="子活动时间" prop="start_at">
          <el-date-picker
            v-model="valueTime"
            type="datetimerange"
            @change="selectTime"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="选择卖场">
          <el-select
            v-model="form.market_id"
            clearable
            disabled
            @change="selectMarket"
            filterable
            placeholder="请选择卖场"
          >
            <el-option
              v-for="item in marketList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关联奖券" style="margin: 0">
          <el-radio v-model="relaStatus" label="0">不关联</el-radio>
          <el-radio v-model="relaStatus" label="1">关联</el-radio>
        </el-form-item>

        <el-form-item label="" v-if="relaStatus == 1">
          <div class="prizeSelect" v-if="Object.keys(selectPrize).length">
            <img :src="selectPrize.img" alt="" />
            {{ selectPrize.name }}
          </div>
          <el-button size="mini" type="primary" @click="openPrizeFn"
            >添加奖券</el-button
          >
        </el-form-item>

        <el-form-item label="状态">
          <el-radio v-model="form.status" label="1">开启</el-radio>
          <el-radio v-model="form.status" label="0">关闭</el-radio>
        </el-form-item>
        <el-form-item label="子活动背景色">
          <!-- <el-input v-model="form.back_color" placeholder="请输入子活动背景色"></el-input> -->
          <colorPicker
            style="border: 1px solid #000; cursor: pointer"
            v-model="form.back_color"
            @change="handleChangeColor"
          />
          {{ form.back_color }}
        </el-form-item>

        <el-form-item label="子活动类型">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in activityType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="抽奖类型">
          <el-select v-model="form.type_sub" placeholder="请选择">
            <el-option
              v-for="item in luckDraw"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动入口图">
          <el-upload
            action="/api/client/base/uploadfile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            ref="upload"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
            :limit="1"
            :headers="myHeaders"
            :file-list="fileList"
            accept="image/jpeg, image/jpg, image/gif, image/png"
            :multiple="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="活动背景图">
          <el-upload
            action="/api/client/base/uploadfile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview_bg"
            ref="upload"
            :on-remove="handleRemove_bg"
            :on-success="handleAvatarSuccess_bg"
            :before-upload="beforeAvatarUpload_bg"
            :auto-upload="true"
            :limit="10"
            :headers="myHeaders"
            :file-list="fileList_bg"
            accept="image/jpeg, image/jpg, image/gif, image/png"
            :multiple="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible_bg">
            <img width="100%" :src="dialogImageUrl_bg" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="排序">
          <el-col :span="5">
            <el-input
              v-model="form.sort"
              placeholder="数字越大越靠后"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="活动说明">
          <VueEditor
            style="width: 100%"
            v-loading="editorLoading"
            element-loading-text="图片上传中"
            element-loading-background="rgba(0, 0, 0, 0.5)"
            useCustomImageHandler
            @image-added="handleImageAdded"
            :editorToolbar="customToolbar"
            v-model="form.content"
          />
        </el-form-item>

        <el-form-item>
          <el-row>
            <el-button type="danger" @click="confirmAdd('form')"
              >立即保存</el-button
            >
            <el-button type="default" @click="cancel()">返回</el-button>
          </el-row>
        </el-form-item>
      </el-form>

      <!-- 子活动配置 -->
      <div v-if="activeName == '2'">
        <prize-table
          ref="prizeFn"
          :typeSub="form.type_sub"
          :activityItemId="id"
          :activityId="activity_id"
          :relId="shopId"
          :marketId="form.market_id"
        ></prize-table>
      </div>
    </div>

    <!-- 关联奖券对话框 -->
    <el-dialog
      title="关联奖券"
      :visible.sync="dialogVisibleRela"
      width="45%"
      @close="closeRelaFn"
    >
      <div class="openBox">
        <span>选择奖券：</span>
        <div style="width: 90%">
          <div
            style="display: flex; justify-content: flex-end; margin-bottom: 5px"
          >
            <el-input
              style="width: 100%"
              v-model="searchPrize"
              placeholder="请输入奖券名称"
              clearable
              @input="clearPrizeFn"
            ></el-input>
            <el-button type="primary" size="small" @click="searchPrizeFn"
              >搜索</el-button
            >
          </div>
          <el-table
            border
            :data="goodsList"
            style="width: 100%; margin: 10px 0"
          >
            <el-table-column align="center" width="50">
              <template slot-scope="scope">
                <el-radio v-model="shopId" :label="scope.row.id">{{
                  ""
                }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              align="center"
              label="奖券主图"
              width="80"
            >
              <template slot-scope="scope">
                <img
                  style="width: 30px; height: 30px"
                  :src="scope.row.img"
                  alt=""
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              align="center"
              label="奖券名称"
              width="auto"
            >
            </el-table-column>
            <el-table-column
              prop="stock"
              align="center"
              label="库存"
              width="auto"
            >
            </el-table-column>
          </el-table>
          <el-pagination
            style="width: 100%"
            @size-change="handleSizeChangePrize"
            @current-change="handleCurrentChangePrize"
            :current-page="pagePrize"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pagesizePrize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalPrize"
            background
          >
          </el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleRela = false">取 消</el-button>
        <el-button type="primary" @click="addPrizeSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
import prizeTable from "@/components/activity/elevenActivity/sonActivity/publicTable/prizeList";
export default {
  components: {
    VueEditor,
    prizeTable,
  },
  // name: 'Vue2Editor',
  data() {
    return {
      validate: false,
      activeName: "1",
      types: [],
      form: {
        name: "",
        // item_id:'',
        pagepath: "",
        start_at: "",
        end_at: "",
        status: "1",
        back_color: "#000",
        back_img: "",
        img: "",
        // video:'',
        sort: 0,
        content: "",
        type: 1,
        // code:''
        type_sub: 11,
        market_id: "",
      },
      // 奖券
      relaStatus: "0", //是否关联奖券
      dialogVisibleRela: false,
      pagePrize: 1,
      pagesizePrize: 5,
      totalPrize: 0,
      searchPrize: "",
      goodsList: [],
      shopId: "",
      selectPrize: {},

      activityType: [
        {
          label: "抽奖",
          value: 1,
        },
      ],

      luckDraw: [
        {
          label: "线上九宫格",
          value: 11,
        },
        {
          label: "线下大屏抽奖",
          value: 12,
        },
        {
          label: "线下手动抽奖",
          value: 13,
        },
      ],

      videoUrl: "", //视频连接
      videoId: "", //视频id
      videoFlag: false,
      videoUploadPercent: 0,

      replaceList: [],

      rules: {
        //   type_id: [
        //     {required: true, message: '请选择文章分类', trigger: 'blur'}
        //   ],
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        // code: [
        //   {required: true, message: '请输入活动编号', trigger: 'blur'},
        // ],
        pagepath: [
          { required: true, message: "请输入跳转页面地址", trigger: "blur" },
        ],
        start_at: [
          { required: true, message: "请选择活动时间", trigger: "blur" },
        ],
      },
      filter_keyword: "",
      editorLoading: false, //富文本图片loading
      customToolbar: [
        [{ header: [false, 1, 2, 3, 4, 5, 6] }], //标题
        ["bold", "italic", "underline", "strike"], //加粗\斜体\下划线\作废
        ["blockquote", "code-block"],
        [
          {
            script: "sub",
          },
          {
            script: "super",
          },
        ], // superscript/subscript
        [
          {
            indent: "-1",
          },
          {
            indent: "+1",
          },
        ], // outdent/indent
        [
          {
            direction: "rtl",
          },
        ],
        [{ align: "" }, { align: "center" }, { align: "right" }], //对齐
        [{ list: "ordered" }, { list: "bullet" }, { list: "check" }], //有序无序列表
        [{ background: [] }, { color: [] }], //背景色
        ["image", "link"], //图片、链接
        ["clean"], //清楚格式（所谓去掉背景色这些花里胡巧）
        ["code"], //代码
        ["code-block"], //代码块
        //['video'] //视频
      ],
      fileList_bg: [],
      dialogImageUrl_bg: "",
      dialogVisible_bg: false,

      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      myHeaders: {
        "access-token": this.$store.state.token, //这里重新定义了请求头
        Authorization: this.$store.state.token,
        "user-id": this.$store.state.user_id,
      },

      valueTime: [],
      id: "", //子活动id
      activity_id: "", //主活动id
      marketList: [],
    };
  },
  mounted() {
    this.remoteMethod()
    this.form.market_id = this.$route.query.market_id*1;
    this.id = this.$route.query.id;
    this.activity_id = this.$route.query.activity_id;
    if (this.id) {
      this.getActivityDetail();
    }
    //this.loadTypes();
  },
  methods: {
    // 获取卖场列表
    remoteMethod() {
      this.$http.post("/api/root/Market/marketList").then((res) => {
        console.log(res, "卖场列表");
        if (res.code == 1) {
          this.marketList = res.data ? res.data : [];
        }
      });
    },
    // 选择卖场
    selectMarket() {},

    // 颜色选择器
    handleChangeColor(val) {
      console.log("输出颜色值", val); // 颜色 #6c8198
      this.form.back_color = val;
    },
    // 获取活动详情
    getActivityDetail() {
      this.$http
        .post("/api/root/activity/son/detail", { id: this.id })
        .then((res) => {
          console.log(res, "子活动详情");
          // if(res.code==1){
          this.form = { ...res.data };
          this.form.status = res.data.status == 1 ? "1" : "0";
          this.shopId = res.data.rel_id;
          this.relaStatus = res.data.rel_arr.length ? "1" : "0";
          this.selectPrize = res.data.rel_arr.length ? res.data.rel_arr[0] : {};
          if (res.data.start_at) {
            let startTime = this.$moment(res.data.start_at * 1000).format(
              "yyyy-MM-DD HH:mm:ss"
            );
            let endTime = this.$moment(res.data.end_at * 1000).format(
              "yyyy-MM-DD HH:mm:ss"
            );
            this.form.start_at = startTime;
            this.form.end_at = endTime;
            this.valueTime = [startTime, endTime];
          }
          // 背景图
          if (res.data.back_img.length > 0) {
            res.data.back_img.map((item) => {
              this.fileList_bg.push({
                url: item.path,
                id: item.id,
              });
            });
          }

          // 主图
          if (res.data.img.length > 0) {
            res.data.img.map((item) => {
              this.fileList.push({
                url: item.path,
                id: item.id,
              });
            });
          }

          // 视频
          // if(res.data.video.length>0){
          //     this.videoUrl = res.data.video[0].path;
          //     this.videoId = res.data.video[0].id
          // }
          // }
        });
    },

    // 切换tabs
    handleClick(e) {
      this.activeName = e.name;
      if (e.name == "2" && this.id) {
        this.$nextTick(() => {
          this.$refs.prizeFn.getShopList();
        });
      }
    },

    // 选择时间
    selectTime() {
      console.log(this.valueTime, "----");
      if (this.valueTime) {
        this.form.start_at = this.$moment(this.valueTime[0]).format(
          "yyyy-MM-DD HH:mm:ss"
        );
        this.form.end_at = this.$moment(this.valueTime[1]).format(
          "yyyy-MM-DD HH:mm:ss"
        );
      }
      console.log(this.form, "000");
    },

    // 背景图
    handleRemove_bg(file, fileList) {
      this.fileList_bg = fileList;
    },
    handlePictureCardPreview_bg(file) {
      console.log("file", file);
      this.dialogImageUrl_bg = file.url;
      this.dialogVisible_bg = true;
    },
    handleAvatarSuccess_bg(res, file, fileList) {
      console.log("fileList", fileList);
      this.fileList_bg = fileList;
    },
    beforeAvatarUpload_bg(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传活动图片大小不能超过 10MB!");
      }
      return isLt2M;
    },

    //   主图
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      console.log("file", file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log("fileList", fileList);
      this.fileList = fileList;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传活动图片大小不能超过 10MB!");
      }
      return isLt2M;
    },

    // 验证视频格式
    beforeUploadVideo(file) {
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
        ].indexOf(file.type) === -1
      ) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 30;
      if (!isLt2M) {
        this.$message.error("上传视频大小不能超过 30MB!");
      }
    },
    // 上传进度显示
    uploadVideoProcess(event, file, fileList) {
      console.log(event.percent, file, fileList);
      this.videoFlag = true;
      this.videoUploadPercent = Math.floor(event.percent);
    },

    // 获取上传地址
    handleVideoSuccess(res, file) {
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      console.log(res, file, "视频上传");
      this.videoUrl = file.response.data.url;
      this.videoId = file.response.data.id;
    },

    // 删除视频按钮
    closeVideo() {
      this.videoUrl = "";
      this.videoId = "";
    },

    confirmAdd(form) {
      this.validateFormData(form);
      if (this.validate) {
        const _ths = this;
        // if(this.form.type_id.length > 0){
        //   this.form.type_id = this.form.type_id.pop();
        // }

        // 背景图
        let bgImg = [];
        if (this.fileList_bg.length > 0) {
          this.fileList_bg.map((v) => {
            if (v.response) {
              bgImg.push(v.response.data.id);
            } else {
              bgImg.push(v.id);
            }
          });
        }

        if (this.relaStatus == 1) {
          if (!this.shopId) {
            this.$message.warning("请选择关联奖券");
            return;
          }
        }

        //   主图
        let imgArr = [];
        if (this.fileList.length > 0) {
          this.fileList.map((v) => {
            if (v.response) {
              imgArr.push(v.response.data.id);
            } else {
              imgArr.push(v.id);
            }
          });
        }
        // this.form.video = this.videoId;
        this.form.back_img = bgImg.join(",");
        this.form.img = imgArr.join(",");
        this.form.item_id = this.id;
        this.form.activity_id = this.activity_id;
        this.form.rel_id = this.shopId;
        let url = this.id
          ? "/api/root/activity/son/edit"
          : "/api/root/activity/son/add";
        this.$http.post(url, { ...this.form }).then((rest) => {
          if (rest.code == 1) {
            this.$message.success(this.id ? "修改成功" : "添加成功");
            setTimeout(function () {
              _ths.$router.back(1);
            }, 800);
          } else {
            this.form = {
              ...this.form,
            };
            this.$message.error(rest.msg);
          }
        });
      }
    },
    cancel() {
      this.$router.back(1);
    },

    /**
     * 验证表单数据
     * @param form
     */
    validateFormData(form) {
      this.$refs[form].validate((valid) => {
        if (!valid) {
          this.$message({
            message: "表单数据未填写完整,操作失败！",
            type: "warning",
          });
          return false;
        }
        this.validate = true;
        return true;
      });
    },
    //富文本上传图片
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var formData = new FormData();
      let isLtSize = file.size / 1024 / 1024 < 10;
      if (!isLtSize) {
        this.$message.warning("上传文件不能超过 10MB!");
        return;
      }
      this.editorLoading = true;
      formData.append("file", file);
      this.$http
        .post("/api/admin/base/uploadfile", formData)
        .then((result) => {
          if (result.msg !== "ok" || !result.data) {
            this.$message.error(result.msg);
            this.editorLoading = false;
            resetUploader();
            return false;
          }
          // 你上传路径返回的url
          let url = result.data.url;
          if (file.type === "video/mp4") {
            Editor.insertEmbed(cursorLocation, "video", url); //视频
          } else if (file.type === "audio/mpeg") {
            Editor.insertEmbed(cursorLocation, "video", url); //音频
          } else {
            Editor.insertEmbed(cursorLocation, "image", url);
          }
          resetUploader();
          this.editorLoading = false;
        })
        .catch((err) => {
          this.editorLoading = false;
        });
    },
    //   loadTypes() {
    //     var _ths = this;
    //     this.$http.post('/api/root/article/articleTypes', {})
    //       .then((rest) => {
    //         if (rest.data.length > 0) {
    //           _ths.types = rest.data;
    //         }
    //       })
    //   },
    handleParentType(value) {
      this.form.pid = value;
      if (this.$refs.organizerUnit) {
        this.$refs.organizerUnit.dropDownVisible = false;
      }
    },

    // 关联奖券
    getShopOkList() {
      let params = {
        keyword: this.searchPrize,
        page: this.pagePrize,
        pagesize: this.pagesizePrize,
        market_id:this.form.market_id
      };
      this.$http.post("/api/root/activity/prize/lists", params).then((res) => {
        console.log(res, "奖品列表");
        if (res.code == 1) {
          this.goodsList = res.data.data ? res.data.data : [];
          this.totalPrize = res.data.count;
        }
      });
    },

    // 添加奖券
    openPrizeFn() {
      this.dialogVisibleRela = true;
      this.getShopOkList();
    },

    // 搜索奖品
    searchPrizeFn() {
      this.pagePrize = 1;
      this.pagesizePrize = 5;
      this.getShopOkList();
    },
    // 清除搜索
    clearPrizeFn() {
      if (this.searchPrize == "") {
        this.pagePrize = 1;
        this.pagesizePrize = 5;
        this.getShopOkList();
      }
    },

    // 添加奖券对话框确定
    addPrizeSubmit() {
      if (!this.shopId) {
        this.$message.warning("请选择奖券");
        return;
      }
      this.selectPrize = this.goodsList.find((item) => {
        if (item.id == this.shopId) {
          return item;
        }
      });
      this.dialogVisibleRela = false;
      console.log(this.selectPrize, "选择的奖品");
    },

    // 关闭对话框
    closeRelaFn() {
      this.searchPrize = "";
      this.pagePrize = 1;
      this.pagesizePrize = 5;
    },

    handleSizeChangePrize(val) {
      this.pagePrize = 1;
      this.pagesizePrize = val;
      this.getShopOkList();
    },
    handleCurrentChangePrize(val) {
      this.pagePrize = val;
      this.getShopOkList();
    },
  },
};
</script>
<style lang="less" scoped>
@import "index.less";
</style>